<template>
  <!--网点维修：工厂返机页面 -->
  <div>
    <!--查询条件 -->
    <el-form :inline="true">
      <el-form-item size="5">
        <el-input placeholder="YSTSN" v-model="searchDto.ystsn" clearable></el-input>
      </el-form-item>
      <el-form-item size="5">
        <el-input placeholder="快递单号" v-model="searchDto.logisticsNum" clearable></el-input>
      </el-form-item>
      <el-form-item size="5">
        <el-input placeholder="返还工厂" v-model="searchDto.backFactory" clearable></el-input>
      </el-form-item>
      <!--返厂批次查询-->
      <el-form-item size="5">
        <el-input placeholder="返厂批次" v-model="searchDto.batch" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchDto.backTime"
          placeholder="选择返厂日期"
          value-format="yyyy-MM-dd"
          format="yyyy 年 MM 月 dd 日"
          type="date"
          :picker-options="pickDate"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData()">查询</el-button>
      </el-form-item>
      <el-form-item v-if="this.roleType === '2' || this.roleType === '3'">
        <!--v-no-more-click为防止重复提交指令-->
        <el-button type="primary" :disabled="receiveFlag" @click="receiveBatchDevice()">批量收机</el-button>
      </el-form-item>
    </el-form>
    <!--一览信息 -->
    <custom-table
      :multipleSelection="this.roleType === '2' || this.roleType === '3'"
      :data="pointReceiveList"
      :columns="columns"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination"
      @selection-change="selectionChange">
    </custom-table>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {apiGetPointReceiveList, apiPostPointReceive, apiPostPointBatchReceive} from '@/api/repairs/point/receive'
  import {getRoleType, getUserId, getName, getOfficeId, getOutsourceId} from '@/utils/token'
  import {parseTime} from '@/utils'

  export default {
    components: {
      CustomTable
    },
    created() {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getPointReceiveList(listQuery)
      this.def()
    },
    data() {
      return {
        // 日期搜索限制
        pickDate: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          }
        },
        // 是否启用批量收机按钮标志量
        receiveFlag: false,
        searchDto: {
          ystsn: undefined,
          logisticsNum: undefined,
          backFactory: undefined,
          batch: undefined,
          backTime: undefined
        },
        roleType: getRoleType(),
        pointType: '',
        pointId: '',
        tableLoadingFlag: false,
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '返还工厂', name: 'factoryName', width: '150', align: 'center'},
          {label: '返还时间', name: 'backTime', width: '180', align: 'center', formatter: this.formatTime},
          {label: '修复结果', name: 'repairResult', width: '100', align: 'center', tag: true, renderHeader: this.renderHeader},
          {label: '返厂批次', name: 'batch', width: '180', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', width: '180', align: 'center'},
          {label: '更新后的YSTSN', name: 'updateAfterYstsn', width: '180', align: 'center'},
          {label: '型号', name: 'modelName', width: '150', align: 'center'},
          {label: '品牌', name: 'brandName', width: '150', align: 'center'},
          {label: '客户姓名', name: 'customerName', width: '150', align: 'center'},
          {label: '客户地址', name: 'customerAddress', align: 'center'},
          {label: '客户联系方式', name: 'customerTel', width: '150', align: 'center'},
          {label: '物流单号', name: 'logisticsNumber', width: '150', align: 'center'},
          {label: '物流公司', name: 'logisticsCompany', width: '150', align: 'center'}
        ],
        operationColumn: {
          width: '80',
          operations: [
            {name: '收机', callback: this.onBtnReceive}
          ]
        },
        pointReceiveList: [],
        // 批量收机List
        selectionList: [],
        // 维修结果已修复
        resultRepaired: '',
        // 维修结果已报废
        resultScrap: '',
        // 维修结果已原物返还
        resultBack: '',
        pagination: this.getData(this.getPointReceiveList),
        listQuery: {
          ystsn: undefined,
          logisticsNum: undefined,
          backFactory: undefined,
          batch: undefined,
          backTime: undefined
        }
      }
    },
    methods: {
      def() {
        if (this.roleType !== '2' && this.roleType !== '3') {
          this.operationColumn = null
        } else {
          if (this.roleType === '2') {
            this.pointType = 0
            this.pointId = getOfficeId()
          } else {
            this.pointType = 1
            this.pointId = getOutsourceId()
          }
        }
      },
      getPointReceiveList(listQuery) {
        if (!listQuery.ystsn) {
          listQuery.ystsn = this.listQuery.ystsn
        }
        if (!listQuery.logisticsNum) {
          listQuery.logisticsNum = this.listQuery.logisticsNum
        }
        if (!listQuery.backFactory) {
          listQuery.backFactory = this.listQuery.backFactory
        }
        if (!listQuery.batch) {
          listQuery.batch = this.listQuery.batch
        }
        if (!listQuery.backTime) {
          listQuery.backTime = this.listQuery.backTime
        }
        this.tableLoadingFlag = true
        apiGetPointReceiveList(listQuery).then(response => {
          this.pointReceiveList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      onBtnReceive(row) {
        this.$confirm('确定收机?', '收机确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let listQuery = {
            id: row.id,
            ystsn: row.ystsn,
            updateAfterYstsn: row.updateAfterYstsn,
            repairResult: row.repairResult,
            pointId: this.pointId,
            pointType: this.pointType,
            unReceiptedNum: 1,
            userId: getUserId(),
            name: getName(),
            batch: row.batch
          }
          apiPostPointReceive(listQuery).then(() => {
            this.$message({
              showClose: true,
              message: '收机成功',
              type: 'success'
            })
            let query = {
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            }
            this.getPointReceiveList(query)
          })
        }).catch(() => {
        })
      },
      searchData () {
        this.listQuery.ystsn = this.searchDto.ystsn
        this.listQuery.logisticsNum = this.searchDto.logisticsNum
        this.listQuery.backFactory = this.searchDto.backFactory
        this.listQuery.batch = this.searchDto.batch
        this.listQuery.backTime = this.searchDto.backTime
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getPointReceiveList(this.listQuery)
      },
      // 为维修结果列添加说明
      renderHeader (h, { column, $index }) {
        return [
          column.label,
          h(
            'el-tooltip',
            {
              props: {
                content: '原物返还收机后自动入不良品库，为待返厂状态',
                placement: 'top'
              }
            },
            [
              h('span', {
                class: {'el-icon-question': true}
              })
            ]
          )
        ]
      },
      // 时间显示格式化
      formatTime (row, column, cellValue) {
        return parseTime(cellValue)
      },
      // 批量收机List
      selectionChange(val) {
        this.selectionList = val
      },
      // 批量收机
      receiveBatchDevice() {
        if (this.selectionList === undefined || this.selectionList.length === 0) {
          this.$message({
            showClose: true,
            message: '未选中任何设备',
            type: 'warn'
          })
          return
        }
        let ids = []
        let batches = []
        this.resultRepaired = 0
        this.resultScrap = 0
        this.resultBack = 0
        for (let i in this.selectionList) {
          ids.push(this.selectionList[i].id)
          batches.push(this.selectionList[i].batch)
          if (this.selectionList[i].repairResult === '已修复') {
            this.resultRepaired ++
          } else if (this.selectionList[i].repairResult === '已报废') {
            this.resultScrap ++
          } else if (this.selectionList[i].repairResult === '原物返还') {
            this.resultBack ++
          }
        }
        this.$confirm('此操作将返回：' + this.resultRepaired + '台已维修设备, ' + this.resultScrap + '台已报废设备, ' + this.resultBack + '台原物返还设备', '收机确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let message = this.$message({
            message: '正在收机中，请耐心等待！',
            type: 'warning',
            duration: 0
          })
          this.receiveFlag = true
          let listQuery = {
            ids: ids,
            batches: batches,
            pointId: this.pointId,
            pointType: this.pointType,
            unReceiptedNum: this.selectionList.length,
            userId: getUserId(),
            name: getName()
          }
          apiPostPointBatchReceive(listQuery).then(() => {
            message.close()
            this.receiveFlag = false
            this.$message({
              showClose: true,
              message: '收机成功',
              type: 'success'
            })
            let query = {
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            }
            this.getPointReceiveList(query)
          }).catch(() => {
            message.close()
            this.receiveFlag = false
          })
        }).catch(() => {
        })
      }
    }
  }
</script>
